//
//  ZPRegisterVerificationViewController.m
//  ZPIOSEducation
//
//  Created by mini1 on 2016/12/13.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPRegisterVerificationViewController.h"
#import "ZPRegisterSelectStuViewController.h"
#import "ZPRegisterInformationViewController.h"
#import "NSString+Emoji.h"
#import "WebViewController.h"
@interface ZPRegisterVerificationViewController () <UITextFieldDelegate>
{
    MBProgressHUD *hud;
}
// App图标
@property (weak, nonatomic) IBOutlet UIImageView  *AppImgView;
// 输入电话号
@property (weak, nonatomic) IBOutlet UITextField  *phoneNumTextField;
// 获取验证码
@property (weak, nonatomic) IBOutlet UIButton     *verificationBtn;
// 输入验证码
@property (weak, nonatomic) IBOutlet UITextField  *verificationTextField;
// 输入密码
@property (weak, nonatomic) IBOutlet UITextField  *passwordTextField;
// 可视登录密码
@property (weak, nonatomic) IBOutlet UIButton     *visibilityPasswordBtn;
// 注册协议
@property (weak, nonatomic) IBOutlet UIButton     *registerProtocolBtn;
// 下一步Btn
@property (weak, nonatomic) IBOutlet UIButton     *nextRegisterBtn;
// 登录Btu
@property (weak, nonatomic) IBOutlet UIButton     *redister_login;

@end

@implementation ZPRegisterVerificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // self.verificationBtn.enabled = NO;
    self.nextRegisterBtn.enabled = NO;
    self.phoneNumTextField.delegate = self;
    self.passwordTextField.delegate = self;
    self.verificationTextField.delegate = self;
    self.passwordTextField.secureTextEntry = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    // hud
    hud = [[MBProgressHUD alloc] initWithView:self.view];
    [hud showAnimated:YES];
    hud.hidden = YES;
    hud.label.text = @"发送中...";
    [self.view addSubview:hud];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    self.view.backgroundColor = zMainColor;
}



- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange) name:UITextFieldTextDidChangeNotification object:nil];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}



#pragma mark - <键盘隐藏>
- (void)dismissKeyboard
{
    [self.phoneNumTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    [self.verificationTextField resignFirstResponder];
}



#pragma mark - <下一步按钮是否可点击>
- (void)textFieldDidChange
{
    //    if (self.phoneNumTextField.text.length == 0) {
    //        self.verificationBtn.enabled = NO;
    //        [self.verificationBtn setBackgroundColor:zFreeColor(255, 255, 255, 0.4)];
    //    } else {
    //        self.verificationBtn.enabled = YES;
    //        [self.verificationBtn setBackgroundColor:UIColorFromRGB(0x0D71A2)];
    //    }
    
    if (self.phoneNumTextField.text.length != 0 && self.verificationTextField.text.length !=0 && self.passwordTextField.text.length != 0) {
        self.nextRegisterBtn.enabled = YES;
        [self.nextRegisterBtn setBackgroundColor:zFreeColor(255, 86, 86, 1.0)];
    } else {
        self.nextRegisterBtn.enabled = NO;
        [self.nextRegisterBtn setBackgroundColor:zFreeColor(255, 255, 255, 0.4)];
    }
}


#pragma mark - <点击获取验证码>
- (IBAction)getVerifcationBtnClick:(id)sender
{
    NSString *mobileNum = self.phoneNumTextField.text;
    if ([mobileNum length] > 0 )
    {
        if ([mobileNum zp_isValidPhoneNum])
        {
            // 验证手机号是否存在
            NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:mobileNum,@"mobile",@"1",@"type", nil];
            hud.hidden = NO;
            [[ZPNetworking sharedZPNetworking] GET:APIPPT@"access/exitsMobileNumber.json" parameters:params progress:^(NSProgress * _Nullable progress) {
                
            } success:^(id  _Nonnull responseObject) {
                
                hud.hidden = YES;
                if ([[responseObject objectForKey:@"code"] integerValue] == 200)
                {
                    if ([[[responseObject objectForKey:@"result"] objectForKey:@"isOk"] boolValue])
                    {
                        [ZPPromptView showMessage:@"该手机号已注册，请登录"];
                    }
                    else
                    {
                        [self getValidateCode]; // 获取验证码
                    }
                }
                else
                {
                    [ZPPromptView showMessage:@"手机号认证失败"];
                }
                
            } failure:^(NSError * _Nonnull error) {
                
                hud.hidden = YES;
                [ZPPromptView showMessage:@"请检查您的网络设置"];
                
            }];
        }
        else
        {
            [ZPPromptView showMessage:@"手机号格式错误"];
        }
    }
    else
    {
        [ZPPromptView showMessage:@"请输入手机号"];
    }
}


- (void)getValidateCode
{
    NSString *mobile = self.phoneNumTextField.text;
    NSDictionary *params = @{
                             @"mobile":mobile,
                             @"type":@"1"
                             };
    hud.hidden = NO;
    [[ZPNetworking sharedZPNetworking] POST:APIPPT@"access/getValidateCode.json" parameters:params progress:^(NSProgress * _Nullable progress) {
        
        
    } success:^(id  _Nonnull responseObject) {
        
        hud.hidden = YES;
        __block int timeout = 60; // 倒计时时间60
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 全局并发队列,默认优先级
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); // 创建事件源-计时器
        dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0); // 没秒执行
        dispatch_source_set_event_handler(_timer, ^{ //控制器执行事件源-计时器
            if (timeout <= 0)
            { // 倒计时超时
                dispatch_source_cancel(_timer);// 结束计时器
                dispatch_async(dispatch_get_main_queue(), ^{ // 回到主线程刷新UI
                    [self.verificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                    self.verificationBtn.enabled = YES;
                    self.verificationBtn.backgroundColor = UIColorFromRGB(0x0D71A2);
                });
            }
            else
            {
                NSString *timeString = [NSString stringWithFormat:@"%d秒后重发",timeout];
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 设置界面的按钮显示,根据自己的需求设置
                    self.verificationBtn.titleLabel.text = timeString;
                    [self.verificationBtn setTitle:timeString forState:UIControlStateNormal];
                    self.verificationBtn.enabled = NO;
                    self.verificationBtn.backgroundColor = zFreeColor(255, 255, 255, 0.4);
                });
                timeout--;
            }
        });
        dispatch_resume(_timer); // 计时器循环执行
        
    } failure:^(NSError * _Nonnull error) {
        
        hud.hidden = YES;
        [ZPPromptView showMessage:@"获取失败，稍后请重试"];
    }];
}



#pragma mark - <密码是否可见>
- (IBAction)isShowPwdButtonClick:(id)sender
{
    UIButton *tempBtn = (UIButton *)sender;
    tempBtn.selected = !tempBtn.selected;
    self.passwordTextField.secureTextEntry = !tempBtn.selected;
}


#pragma mark - <点击下一步>
- (IBAction)RegisterNextBtnClick:(id)sender
{
//    ZPRegisterInformationViewController*informationVc = [[ZPRegisterInformationViewController alloc] init];
//    [self.navigationController pushViewController:informationVc animated:YES];
    
    NSString *mobileNum = self.phoneNumTextField.text;
    if (mobileNum.length == 0 || ![mobileNum zp_isValidPhoneNum]) {
        [ZPPromptView showMessage:@"手机号格式错误"];
        return;
    }
    
    NSString *code = self.verificationTextField.text;
    if (code.length == 0) {
        [ZPPromptView showMessage:@"请输入验证码"];
        return;
    }
    
    NSString *password = self.passwordTextField.text;
    if (password.length < 6 || password.length > 20) {
        UIAlertView  *alert = [[UIAlertView  alloc] initWithTitle:@"提示" message:@"密码长度为6~20位" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert  show];
        return;
    }
    
    if ([password containsString:@" "]||[password containsEmoji]) {
        [ZPPromptView showMessage:@"密码不能包含特殊字符或空格"];
        return;
    }
    
    NSDictionary *params = @{@"mobile":mobileNum,
                             @"validateCode":code,
                             @"password":[password zp_md5String],
                             @"idfv":@"0"
                             };
    
    
    [[ZPNetworking sharedZPNetworking] POST:APIPPT@"access/onRegister.json" parameters:params progress:^(NSProgress * _Nullable progress) {
        
        
    } success:^(id  _Nonnull responseObject) {
        
        ZPLog(@"responseObject == %@",responseObject);
        
        hud.hidden = YES;
        if ([[responseObject objectForKey:@"code"] integerValue] == 200)
        {
            if ([responseObject valueForKey:@"result"])
            {
                
                NSMutableDictionary *userInfo=[NSMutableDictionary changeType:[responseObject objectForKey:@"result"]];
                [userInfo setValue:password forKey:@"passwd"];
                [userInfo setValue:mobileNum forKey:@"userName"];
                NSString *memeberId = [NSMutableDictionary changeType:[userInfo objectForKey:@"memberId"]];
                 [userInfo setValue:memeberId forKey:@"memberId"];
                [ZPPromptView showMessage:@"注册成功，完善个人信息"];
                ZPRegisterInformationViewController *vc = [[ZPRegisterInformationViewController alloc] init];
      
                vc.userDic = userInfo;
                vc.isFirstCreat = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
            else
            {
                [ZPPromptView showMessage:[responseObject objectForKey:@"codeMsg"]];
            }
        }
        else
        {
            [ZPPromptView showMessage:[responseObject objectForKey:@"codeMsg"]];
        }
    } failure:^(NSError * _Nonnull error) {
        
        hud.hidden = NO;
        [ZPPromptView showMessage:@"请检查网络，稍后重试"];
    }];
    
}



#pragma mark - <点击登录按钮>
- (IBAction)loginBtnClick:(id)sender
{
//     [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - <点击注册协议>
- (IBAction)registerProtocolBtnClick:(id)sender
{
    WebViewController *vc=[[WebViewController alloc]init];
    vc.urlS = APICOMMUNITY@"index.php/page/index/2";
    [self.navigationController pushViewController:vc animated:YES];
    
}



#pragma mark - <UITextFieldDelegate>
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
